#include "data_broadcast.h"

// 将广播消息保存到文件
int save_broadcast_to_file(const char *sender, const char *message) {
    FILE *fp = fopen(BROADCAST_FILE, "a");
    if (fp == NULL) {
        perror("Failed to open broadcast file");
        return -1;
    }

    fprintf(fp, "[%s] %s\n", sender, message);
    fclose(fp);
    return 0;
}

// 向多个客户端广播消息，并保存到文件
int data_broadcast(int *client_socks, int client_count, const char *sender, const char *message) {
    NetMsg broadcast_msg;
    broadcast_msg.type = MSG_BROADCAST;
    strncpy(broadcast_msg.sender, sender, MAX_ACCOUNT_LEN - 1);
    broadcast_msg.sender[MAX_ACCOUNT_LEN - 1] = '\0';
    strncpy(broadcast_msg.content, message, MAX_MSG_LEN - 1);
    broadcast_msg.content[MAX_MSG_LEN - 1] = '\0';

    // 保存广播消息到文件
    if (save_broadcast_to_file(sender, message) != 0) {
        return -1;
    }

    // 向所有客户端发送广播消息
    for (int i = 0; i < client_count; i++) {
        if (send(client_socks[i], &broadcast_msg, sizeof(NetMsg), 0) == -1) {
            perror("send() failed");
            // 可以在这里添加移除无效客户端的逻辑
            return -1;
        }
    }
    return 0;
}

// 客户端接收广播消息
int receive_broadcast(int client_sock, NetMsg *received_msg) {
    int bytes_received = recv(client_sock, received_msg, sizeof(NetMsg), 0);
    if (bytes_received == -1) {
        perror("recv() failed");
        return -1;
    } else if (bytes_received == 0) {
        printf("Connection closed by the server.\n");
        return 0;
    }
    return bytes_received;
}

// 显示接收到的广播消息
void display_broadcast(const NetMsg *msg) {
    printf("\033[1;33m[Broadcast from %s]: %s\033[0m\n", msg->sender, msg->content);
}

